const { execSync } = require('child_process');
const { dialog } = require('electron');

/**
 * 检测 PostgreSQL 是否存在
 * @returns {Promise<boolean>}
 */
function hasPostgreSQL() {
  const cmds = {
    darwin: 'which psql',
    win32:  'where psql',
    linux:  'which psql'
  };
  const cmd = cmds[process.platform];
  if (!cmd) return Promise.resolve(false);

  return new Promise(resolve => {
    try {
      execSync(cmd, { stdio: 'ignore' });
      resolve(true);
    } catch {
      resolve(false);
    }
  });
}

/**
 * 弹出自定义安装向导
 */
async function promptInstall(win) {
  const buttons = {
    darwin: ['一键安装 (Homebrew)', '以后再说'],
    win32:  ['一键安装 (Chocolatey)', '以后再说'],
    linux:  ['一键安装 (apt/yum)', '以后再说']
  };
  const { response } = await dialog.showMessageBox(win, {
    type: 'info',
    title: '缺少 PostgreSQL',
    message: '本应用需要 PostgreSQL 数据库才能运行。',
    detail: '点击下方按钮可自动安装，安装完成后请重启应用。',
    buttons: buttons[process.platform] || buttons.linux
  });

  if (response === 0) {
    installPostgreSQL(win);
  }
}

/**
 * 真正执行安装
 */
function installPostgreSQL(win) {
  const scripts = {
    darwin: '/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" && brew install postgresql',
    win32:  'powershell -Command "Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = 3072; iex ((New-Object System.Net.WebClient).DownloadString(\'https://chocolatey.org/install.ps1\')); choco install postgresql"',
    linux:  'sudo apt update && sudo apt install -y postgresql postgresql-contrib'
  };
  const script = scripts[process.platform] || scripts.linux;

  try {
    execSync(script, { stdio: 'inherit' });
    dialog.showMessageBox(win, {
      type: 'info',
      title: '安装完成',
      message: 'PostgreSQL 已安装，请重启应用。'
    });
  } catch (e) {
    dialog.showErrorBox('安装失败', e.message);
  }
}

module.exports = { hasPostgreSQL, promptInstall };